package com.crazyice.lee.reader;

import com.alibaba.fastjson.JSON;
import com.crazyice.lee.data.Student;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Random;

@Slf4j
public class KafkaSender {
    private static Properties properties;

    private static final String kafkaTopic = "student";

    private static KafkaProducer<String, String> producer;
    private static Random r;

    private static void init() {
        properties = new Properties();
        try(InputStream inputStream = KafkaSender.class.getResourceAsStream("/kafka.properties")) {
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        init();
        producer = new KafkaProducer<>(properties);
        r=new Random();
        while (true) {
            Thread.sleep(100); // 每三秒发送过一次
            sendUrlToKafka(); // 发送kafka消息
        }
    }

    private static void sendUrlToKafka() {
        Student student = new Student(r.nextInt(100000),"aaa"+r.nextInt(10),"ppp"+r.nextInt(50),r.nextBoolean(),r.nextInt(30));
        String msgContent = JSON.toJSONString(student);
        log.info("{}",msgContent);
        ProducerRecord record = new ProducerRecord<String, String>(kafkaTopic, null, null, msgContent);
        producer.send(record);
        producer.flush();
    }
}